
#include "xapp_config.h"

#if USER_CHECK_ENABLED( SYSTEM )

#include <string.h> 

#include "xapp_auto_k.h"
#include "xapp_system.h"


#include "system_list.h"

#include "xtask+app.h"

#if USER_CHECK_LOG_ENABLED( SYSTEM )
#include "log.h"
#define LOG     LOG_INFO 
#define LOG0    LOG_INFO0 
#define LOG1    LOG_INFO1
#define LOG2    LOG_INFO2
#define LOG3    LOG_INFO3
#else 
#define LOG(...) 
#define LOG0(...)
#define LOG1(...)
#define LOG2(...)
#define LOG3(...)
#endif 

static user_system_desc_t const * mpsys = NULL;

void xapp_system_init(void)
{
    mpsys = NULL;
    xapp_system_timer_create();
    
    // use to task to start system 
#if USER_CHECK_ENABLED( AUTO_K )
    if( xapp_auto_k_init() == false )
#endif 
    {
        xapp_system_set_mode( SYSTEM_MODE_BOOT );
    }    
}

const user_system_desc_t* xapp_system_current(void)
{
    return mpsys;
}

void xapp_system_timer_timeout(void)
{
    msg_t   msg;
    msg.type = MSG_TYPE_SYSTEM; 
    msg.sub_type = MSG_SYSTEM_TYPE_TIMER_TIMEOUT;

    
    xtask_app_send_msg( &msg, __LINE__ );
}

void xapp_system_set_mode( system_mode_t mode )
{
    // use this to send task 
    msg_t   msg;
    msg.type = MSG_TYPE_SYSTEM;
    msg.sub_type = MSG_SYSTEM_TYPE_UPDATE_MODE;
    msg.param = (uint32_t)mode;
    xtask_app_send_msg( &msg, __LINE__ );
}


void xapp_system_update_by( system_mode_t mode )
{
    // LOG0("system mode update!!!");
    if( mpsys != NULL && mpsys->mode == mode ) 
    {
        return; 
    }
    
    if( mpsys != NULL ) 
    {
        mpsys->function.destroy(); 
    }
    
    switch( mode ) 
    {
        case SYSTEM_MODE_BOOT:          mpsys = &gsSYSTEM_BOOT;     break;
        case SYSTEM_MODE_NORMAL:        mpsys = &gsSYSTEM_NORMAL;   break;

#if SYSTEM_MODE_DFU_ENABLE
        case SYSTEM_MODE_DFU:           mpsys = &gsSYSTEM_DFU;      break; 
#endif // !SYSTEM_MODE_DFU_ENABLE      

        case SYSTEM_MODE_POWER_OFF:     mpsys = &gsSYSTEM_POWEROFF; break;

#if SYSTEM_MODE_TPDFU_ENABLE
        case SYSTEM_MODE_TPDFU:         mpsys = &gsSYSTEM_TPDFU;    break;
#endif // !SYSTEM_MODE_TPDFU_ENABLE

#if SYSTEM_MODE_FACTORY_TEST_ENABLE
        case SYSTEM_MODE_FACTORY_TEST:  mpsys = &gsSYSTEM_FACTORY_TEST; break;
#endif // !SYSTEM_MODE_FACTORY_TEST_ENABLE

#if SYSTEM_MODE_AUTO_K_ENABLE
        case SYSTEM_MODE_AUTO_K:        mpsys = &gsSYSTEM_AUTO_K; break;
#endif // !SYSTEM_MODE_AUTO_K_ENABLE
        
        case SYSTEM_MODE_RESET:         mpsys = &gsSYSTEM_RESET;    break;
        default:                        mpsys = &gsSYSTEM_BOOT;     break;

    }
    
    if( mpsys != NULL ) 
    {
        mpsys->function.init();
    }    
}

void xapp_system_on_time_elapsed( uint8_t flag ) 
{
    if( mpsys != NULL )
    {
        mpsys->function.task_loop( flag );
    }
}

//void xapp_system_set_tpdfu_mode( void )
//{
//    xapp_system_set_mode(SYSTEM_MODE_TPDFU);
//}

#endif // !USER_CHECK_ENABLED( SYSTEM )

// ua system loop 
